<template>
  <div class="equipmentStatusReport_main main_container">
    <div v-if="!selectedRow.selectedId" class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-if="!selectedRow.selectedId" v-loading="loading" class="main_main">
      <search-bar-new :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          v-if="tableColumns.length>0"
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          style="width: 99.9%"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" align="center" />
          <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" />
        </el-table>
      </div>
    </div>
    <div v-if="!selectedRow.selectedId" class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>

    <div v-if="selectedRow.selectedId" class="main_header">
      <div class="padding_container">
        <div class="left">
          <a class="left_button" @click="()=>{selectedRow.selectedId = ''; selectedRow.selectedName=''}">
            <svg-icon icon-class="返回" />
            返回
          </a>
        </div>
        <div class="right" />
      </div>
    </div>

    <div v-if="selectedRow.selectedId" class="main_main detail_container">

      <div class="deviceName_div">
        {{ selectedRow.selectedName }}
      </div>
      <div class="SearchBar_main main_main_search">
        <div class="main_main_search_item">
          <div class="name">查询日期</div>
          <div class="value">
            <el-date-picker
              v-model="selectedRow.selectTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              :editable="false"
              @clear="getDetailData()"
            />
          </div>
        </div>
        <div class="main_main_search_item last_item">
          <a class="button" @click.stop="getDetailData">
            搜索
          </a>
          <a class="button" @click.stop="refreshDate">
            刷新
          </a>
        </div>
      </div>
      <div class="detail_container_top detail_container_padding">
        <div
          class="detail_container_top_weblist"
          :style="{ borderColor: webListData.color }"
        >
          <div
            v-for="(item, index) in webListData.lineList"
            :key="index"
            class="weblist_item"
            :style="{
              marginLeft: item.marginLeft,
              backgroundColor: item.color,
              width: item.width?item.width:'unset',
              flex:item.flex?1:'unset'
            }"
          />
        </div>

        <div
          class="detail_container_top_ruler"
          :style="{ backgroundImage: 'url(' + backgroundImage + ')' }"
        />
      </div>
      <div class="detail_container_middle detail_container_padding">
        <div id="map4" class="middle_left" />
        <div class="middle_right">
          <div class="middle_right_top">
            OEE：
            <div class="middle_right_top_value">{{ detailData.useRate }}</div>
          </div>
          <div class="middle_right_bottom">
            <el-table
              ref="table2"
              :data="detailData.realStatus"
              stripe
              border
            >
              <el-table-column prop="status" label="实时状态">
                <template slot-scope="scope">
                  <div class="status_show">
                    <div v-if="scope.row.status=='运行'" class="status_show_tag" style="background-color: #4DEE9D " />
                    <div v-if="scope.row.status=='报警'" class="status_show_tag" style="background-color: #FF9292 " />
                    <div v-if="scope.row.status=='空闲'" class="status_show_tag" style="background-color: #FFCA74 " />
                    <div v-if="scope.row.status=='离线'" class="status_show_tag" style="background-color: #999999 " />
                    <div v-if="scope.row.status=='急停'" class="status_show_tag" style="background-color: #FF2E2E " />
                    <div class="status_show_name">{{ scope.row.status }}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="allTime"
                label="总时间"
              />
              <el-table-column
                prop="count"
                label="总次数"
              />
            </el-table>
          </div>
        </div>
      </div>
      <div ref="table3" class="detail_container_bottom detail_container_padding">

        <el-table
          ref="table3"
          :data="detailData.webList"
          :max-height="300"
          stripe
          border
          :cell-style="cellStyle"
        >
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column prop="runningStatusName" label="实时状态" />
          <el-table-column
            prop="startTime"
            label="开始时间"
          />
          <el-table-column
            prop="endTime"
            label="结束时间"
          />
          <el-table-column
            prop="lastTimeStr"
            label="持续时间"
          />
        </el-table>
      </div>
    </div>

  </div>
</template>

<script>
import { list, cncStatusDetails } from '@/api/equipmentManage/equipmentReport/equipmentStatusReport'
import { mapGetters } from 'vuex'
const backgroundImage = require('@/assets/images/equipmentManage/timeline_common.svg')
import moment from 'moment'
export default {
  name: 'Index',

  computed: {
    ...mapGetters([
      'companyId', 'windowResizeTag'
    ])
  },
  data() {
    return {
      backgroundImage: backgroundImage,
      loading: true,
      pageId: '设备状态统计', // 页面唯一标识
      pageExportId: '设备状态统计导出',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableHeight3: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'realStatus', label: '实时状态', canOrder: false },
        { prop: 'deviceName', label: '设备信息', canOrder: false },
        { prop: 'runTime', label: '运行时长' },
        { prop: 'freeTime', label: '空闲时长' },
        { prop: 'alarmTime', label: '报警时长' },
        { prop: 'offlineTime', label: '离线时长' },
        { prop: 'oee', label: 'OEE', canOrder: false }
      ],
      exportTableColumns: [// 表格常规字段（初始值）
        { prop: 'realStatus', label: '实时状态', canOrder: false },
        { prop: 'deviceName', label: '设备信息', canOrder: false },
        { prop: 'runTime', label: '运行时长' },
        { prop: 'freeTime', label: '空闲时长' },
        { prop: 'alarmTime', label: '报警时长' },
        { prop: 'offlineTime', label: '离线时长' },
        { prop: 'oee', label: 'OEE', canOrder: false }
      ],
      defaultExport: [],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'searchValue', label: '模糊搜索', type: 'input' },
        // { prop: 'deviceName', label: '设备信息', type: 'input' },
        { prop: 'realStatus', label: '实时状态', type: 'select', optionsName: 'statusOptions' }
      ],

      operationData: [ // 右上角的操作按钮
        { label: '批量导出3', perm: 'equipmentManage:equipmentStatusReport:export' },
        { label: '页面配置', perm: '' }
      ],

      statusOptions: [ // 选择组件数据源
        { value: undefined, label: '全部' },
        // { value: '未知', label: '未知' },
        // { value: '在线', label: '在线' },
        { value: '运行', label: '运行' },
        { value: '空闲', label: '空闲' },
        { value: '报警', label: '报警' },
        { value: '离线', label: '离线' },
        { value: '急停', label: '急停' }
      ],
      selectedRow: {
        selectedId: '',
        selectedName: '',
        selectTime: moment(new Date()).format('YYYY-MM-DD')
      },
      webListData: {},
      detailData: {},
      myChart: undefined
    }
  },
  watch: {
    'selectedRow.selectTime'() {
      if (this.selectedRow.selectTime == null) {
        this.getDetailData()
      }
    },
    windowResizeTag() {
      if (this.myChart) {
        this.$nextTick(() => {
          setTimeout(() => {
            this.$nextTick(() => {
              this.drawLine()

              this.tableHeight3 =
              document.getElementsByClassName('detail_container ')[0].clientHeight -
              document.getElementsByClassName('detail_container_top  ')[0].clientHeight -
              document.getElementsByClassName('detail_container_middle  ')[0].clientHeight -
                140
            })
          }, 500)
        })
      }
    }
  },
  mounted() {
  },
  methods: {
    cellStyle({ row, column }) {
      if (column.property == 'realStatus' || column.property == 'runningStatusName') {
        if (row.realStatus == '运行' || row.runningStatusName == '运行') {
          return { color: '#00D067' }
        }
        if (row.realStatus == '报警' || row.runningStatusName == '报警') {
          return { color: '#EE4545' }
        }
        if (row.realStatus == '空闲' || row.runningStatusName == '空闲') {
          return { color: '#E8A538' }
        }
        if (row.realStatus == '离线' || row.runningStatusName == '离线') {
          return { color: '#666666' }
        }
        if (row.realStatus == '急停' || row.runningStatusName == '急停') {
          return { color: '#FF2E2E' }
        }
      }

      if (column.property == 'deviceName') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'deviceName':
          this.showDetail(row)
          break
      }
    },
    showDetail(row) {
      this.selectedRow.selectedId = row.id
      this.selectedRow.selectedName = row.deviceName

      this.selectedRow.selectTime = moment(new Date()).format('YYYY-MM-DD')
      this.getDetailData()
    },
    getList() {
      list(this.pageData).then(res => {
        this.tableData = res.data
        this.total = res.total
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
        })
      })
    },
    getExportData(data) {
      return list(data)
    },
    refresh() {
      this.pageData.pageNum = 1
      this.getList()
    },
    refreshDate() {
      this.selectedRow.selectTime = moment(new Date()).format('YYYY-MM-DD')
      this.getDetailData()
    },
    getDetailData() {
      cncStatusDetails({ ...this.selectedRow, id: this.selectedRow.selectedId }).then(res => {
        this.detailData = res.data
        this.handleWebList(res.data.webList)

        this.$nextTick(() => {
          this.drawLine()

          this.tableHeight3 = this.$refs.table3.offsetHeight
        })
      })
    },
    handleWebList(webList) {
      const colors = ['#4DEE9D', '#FF9292', '#FFCA74', '#999999', '#FF2E2E']
      const statuses = ['RUN', 'ALARM', 'STOP', 'OFFLINE', 'EMER']
      this.webListData = {}
      const cacheData = {}
      if (webList.length > 0) {
        cacheData.lineList = webList.map((item, index) => {
          item.color = colors[statuses.indexOf(item.runningStatus)]
          if (item.endTime.split(' ')[1] == '23:59:59') {
            item.flex = 1
          } else {
            console.log(item.lastTime)
            const s = item.lastTime
            item.width = `${(s / (24 * 60 * 60)).toFixed(4) * 100}%`
          }
          if (index == 0) {
            const startTime = this.time_to_sec(item.startTime.split(' ')[1])
            item.marginLeft = `${(startTime / (24 * 60 * 60)).toFixed(4) *
              100}%`
          } else {
            item.marginLeft = 0
          }
          return item
        })
        console.log(webList)
      }
      cacheData.color = colors[statuses.indexOf(webList[webList.length - 1].runningStatus)]
      console.log(cacheData)
      this.webListData = cacheData
    },
    time_to_sec(time) {
      var s = ''

      var hour = time.split(':')[0]
      var min = time.split(':')[1]
      var sec = time.split(':')[2]

      s = Number(hour * 3600) + Number(min * 60) + Number(sec)

      return s
    },

    drawLine() {
      const data = this.detailData
      // 处理饼图的数据
      const echartsData = []
      const echartsColor = []
      if (data.runPer != '0.00%') {
        const runData = {
          name: '运行',
          value: data.runPer.replace('%', ''),
          percent: data.runPer
        }
        echartsData.push(runData)
        echartsColor.push('#4DEE9D')
      }
      if (data.alarmPer != '0.00%') {
        const alarmData = {
          name: '报警',
          value: data.alarmPer.replace('%', ''),
          percent: data.alarmPer
        }
        echartsData.push(alarmData)
        echartsColor.push('#FF9292')
      }
      if (data.freePer != '0.00%') {
        const freeData = {
          name: '空闲',
          value: data.freePer.replace('%', ''),
          percent: data.freePer
        }
        echartsData.push(freeData)
        echartsColor.push('#FFCA74')
      }
      if (data.offlinePer != '0.00%') {
        const offlineData = {
          name: '离线',
          value: data.offlinePer.replace('%', ''),
          percent: data.offlinePer
        }
        echartsData.push(offlineData)
        echartsColor.push('#999999')
      }
      if (data.emerPer != '0.00%') {
        const offlineData = {
          name: '急停',
          value: data.emerPer.replace('%', ''),
          percent: data.emerPer
        }
        echartsData.push(offlineData)
        echartsColor.push('#FF2E2E')
      }
      if (this.myChart) {
        this.$echarts.init(document.getElementById('map4')).dispose()
      }
      this.myChart = this.$echarts.init(document.getElementById('map4'))
      this.myChart.setOption({
        tooltip: {
          trigger: 'item'
        },
        // 右边信息面板
        legend: {
          orient: 'vertical',
          right: '10%',
          top: 'middle',
          itemHeight: 15,
          itemWidth: 30,
          itemGap: 30,

          textStyle: {
            color: '#000000',
            fontSize: 16,
            padding: [0, 25]
          }
        },
        // polar: {
        //   center: ['50%', '50%'],
        //   radius: '140%' // 图形大小
        // },
        color: echartsColor,
        series: [
          {
            name: '设备状态统计',
            type: 'pie',
            radius: ['44%', '66%'],
            center: ['30%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 3
            },

            label: {
              // alignTo: 'labelLine', // ! 文字对齐方式
              formatter: function(e) {
                const {
                  data: { name, percent }
                } = e
                return `{a|${name} ${percent}}\n\n`
              },
              rich: {
                a: { fontSize: 12, color: '#000000', padding: [0, -70] },
                c: { fontSize: 12, align: 'left', color: '#666666', padding: [8, 0, 0, 8] }
              }
            },
            labelLine: {
              length: 20,
              length2: 80,
              lineStyle: {
                color: '#D8D8D8'
              }
            },
            data: echartsData
          }
        ]

      })
    }
  }
}
</script>

<style lang="less" scoped>

.left_button{
  color: #333333;
  padding: 0px 15px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  font-size: 14px;
  /deep/ .svg-icon{
    margin-right: 10px;
  }
}
.left_button:hover{
  background-color: rgba(56,123,252,.5);
  color: #fff;
}
.detail_container{
  height: calc(100% - 70px);
  overflow-y: auto;
  .main_main_search{
    //border-bottom: 1px solid #BACBEC;
    height: 50px;min-height: 50px;
    margin: 0 20px;
    padding: 0 !important;
    display: flex;
    align-items: center;
  }
  .main_main_search_item{
    margin-top: 0 !important;
    padding-left: 0 !important;
  }
  .deviceName_div{
    height: 50px;
    min-height: 50px;
    padding-left: 20px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #BACBEC;
  }
  .detail_container_padding{
    margin: 10px 20px 0 20px;
  }
  .detail_container_top{
    .detail_container_top_weblist{
      height:50px;display: flex;align-items: center;border-radius: 6px;
      border: 3px solid #FFFFFF;
      .weblist_item{
        height: 100%;
      }
      .weblist_item:first-child{
        border-radius: 4px 0 0 4px;
      }
      //.weblist_item:last-child{
      //  border-radius: 0 4px  4px 0;
      //}
    }
    .detail_container_top_ruler{
      height: 50px;
      color: #333333;
      background-size: 100% auto;
      background-repeat: no-repeat;margin-top: 5px;margin-left: 3px;
    }
  }
  .detail_container_middle{
    display: flex;margin-top: 0;
    .middle_left{
      width: 50%;
      margin-top: 20px;
      position: relative;
    }
    .middle_left:after {
      content: "";
      position: absolute;
      top: 12.5%;
      right: 1px;
      height: 75%;
      width: 1px;
      background-color: #BACBEC;
    }
    .middle_right{
      width: 50%;
      margin-top: 20px;
      .middle_right_top{
        display: flex;justify-content: flex-end;align-items: flex-end;
        font-size: 20px;color: #000000;
        .middle_right_top_value{
          font-size: 36px;
          color: #666666;
          line-height: 36px;
        }
      }
      .middle_right_bottom{
        margin-left: 20px;
        margin-top: 20px;
        .status_show{
          display: flex;align-items: center;
          .status_show_tag{
            width: 27px;
            height: 13px;
            border-radius: 4px;
          }
          .status_show_name{
            padding-left: 10px;
          }
        }
      }
    }
  }
  .detail_container_bottom{
    flex: 1;
  }
}

</style>
